xquery version "1.0";

(: $Id: devguide_xquery.xml 15318 2011-09-07 19:43:24Z dizzzz application/xquery $ :)

import module namespace request="http://exist-db.org/xquery/request";
import module namespace session="http://exist-db.org/xquery/session";
import module namespace util="http://exist-db.org/xquery/util";
import module namespace  fn="http://www.w3.org/2005/xpath-functions";

declare option exist:serialize "method=xhtml media-type=text/xml";

declare function local:transformerIsfet($sequence as item()*) as element()*
{
    let $count := count($sequence)
    let $seqelem := ('timeStamp', 'status', 'probeType', 'Vs', 'pH', 'Vt', 'temperature', 'pid')
    
    return
    	if ($count = 8) then (: Verify fields number of ISFET Data :)
		let $res1 := for $item at $id in $sequence
          		return
          			<metadata attribute='{$seqelem[$id]}'>{$item}</metadata>
          	return local:validateIsfet($res1, $count + 1)
       	else 
       		<metadata attribute='error'>measurement length {$count} is not the needed length </metadata>
     
};

declare function local:validateIsfet($seq as element()*, $pos as xs:integer) as element()*
{
	let $valiAttr := 'validation'
	let $validation_status := ('PreValidated', 'YES', 'NOT')
	
	return if (fn:number($seq[@attribute="status"]) != 0 or (fn:number($seq[@attribute="Vt"]) > 4000) or ((fn:number($seq[@attribute="Vt"]) > 3200) and (fn:number($seq[@attribute="Vs"]/text()) > 3500))) then
		insert-before($seq, $pos , (<metadata attribute='{$valiAttr}'>{$validation_status[3]}</metadata>))
	else
		insert-before($seq, $pos , (<metadata attribute='{$valiAttr}'>{$validation_status[1]}</metadata>))
};

declare function local:main() as element()*
{
	(: recuperation des parametres du request :)
	let $nodeID := request:get-parameter("nodeID", "")
	let $memory := request:get-parameter("memory", "")
	let $data_id := request:get-parameter("data_id", "")
	let $configID := request:get-parameter("configID", "")
	
	(: recuperation des donnees :)
	let $binary := util:binary-doc($data_id)
	let $input := util:binary-to-string($binary)
	
	let $delimeter := if (not ($configID))
                  then ';'
                  else ';'
	
	let $sequence := tokenize($input, $delimeter)
	
	return 	local:transformerIsfet($sequence)
};

<metalist>

{local:main()}

</metalist>

